package com.example.caorl.jdbc.dao.impl;

import com.example.caorl.jdbc.dao.IMallOrderDAO;
import com.example.caorl.jdbc.domain.MallOrder;
import com.example.caorl.jdbc.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

public class MallOrderDAOImpl implements IMallOrderDAO {

    @Override
    public void savePrepare(MallOrder mallOrder) {
        Connection conn = null;
        PreparedStatement ps = null;
        String sql = "INSERT INTO mall_order(order_sn, order_status, aftersale_status, consignee, mobile) " +
                "VALUES(?,?,?,?,?)";
        try {
            conn = JDBCUtil.getConn();
            // 关闭自动提交:
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);
            //这里的索引从1开始，而不是0
            ps.setString(1, mallOrder.getOrderSn());
            ps.setShort(2, mallOrder.getOrderStatus());
            ps.setInt(3, mallOrder.getAftersaleStatus());
            ps.setString(4, mallOrder.getConsignee());
            ps.setString(5, mallOrder.getMobile());
            ps.executeUpdate();//无参数
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            JDBCUtil.rollback(conn);
        } finally {
            JDBCUtil.reset(conn);
        }
        JDBCUtil.close(conn, ps, null);
    }



    private String buildField(Object obj) {
        return  obj==null?"null":("'"+obj.toString()+"'");
    }

    @Override
    public void saveStat(MallOrder mallOrder) {
        Connection conn = null;
        Statement ps = null;
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO mall_order(order_sn, order_status, aftersale_status, consignee, mobile) VALUES(");
        sb.append(buildField(mallOrder.getOrderSn())).append(",")
          .append(buildField(mallOrder.getOrderStatus())).append(",")
          .append(buildField(mallOrder.getAftersaleStatus())).append(",")
          .append(buildField(mallOrder.getConsignee())).append(",")
          .append(buildField(mallOrder.getMobile())).append(")");
        try {
            conn = JDBCUtil.getConn();
            // 关闭自动提交:
            conn.setAutoCommit(false);
            ps = conn.createStatement();
            ps.executeUpdate(sb.toString());
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            JDBCUtil.rollback(conn);
        } finally {
            JDBCUtil.reset(conn);
        }
        JDBCUtil.close(conn, ps, null);
    }
}
